package com.example.demo.service;

import com.example.demo.mapper.VipOrderMapper;
import com.example.demo.mapper.ProductMapper;
import com.example.demo.mapper.UserCreditMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.Product;
import com.example.demo.model.User;
import com.example.demo.model.UserCredit;
import com.example.demo.model.VipOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class StoreService {
    private final ProductMapper productMapper;
    private final VipOrderMapper orderMapper;
    private final UserCreditMapper userCreditMapper;
    private final UserMapper userMapper;

    @Autowired
    public StoreService(ProductMapper productMapper, VipOrderMapper vipOrderMapper,
                        UserCreditMapper userCreditMapper, UserMapper userMapper) {
        this.productMapper = productMapper;
        this.orderMapper = vipOrderMapper;
        this.userCreditMapper = userCreditMapper;
        this.userMapper = userMapper;
    }

    public List<Product> getAvailableProducts() {
        return productMapper.findAvailableProducts();
    }

    @Transactional
    public Map<String, Object> purchaseProduct(Long userId, Long productId) {
        Map<String, Object> response = new HashMap<>();

        // 检查商品
        Product product = productMapper.findById(productId);
        if (product == null || (product.getStock() == 0 && product.getStock() != -1)) {
            response.put("success", false);
            response.put("message", "商品不存在或库存不足");
            return response;
        }

        // 检查积分
        UserCredit credit = userCreditMapper.findByUserId(userId);
        if (credit == null || credit.getBalance() < product.getPrice()) {
            response.put("success", false);
            response.put("message", "积分不足");
            return response;
        }

        // 创建订单
        VipOrder order = new VipOrder();
        order.setUserId(userId);
        order.setProductId(productId);
        order.setPrice(product.getPrice());
        order.setStatus("PENDING");
        order.setCreatedAt(LocalDateTime.now());  // 添加这行
        order.setUpdatedAt(LocalDateTime.now());  // 添加这行
        orderMapper.insertOrder(order);

        try {
            // 扣除积分
            int newBalance = credit.getBalance() - product.getPrice();
            int updated = userCreditMapper.updateBalanceWithLock(userId, credit.getBalance(), newBalance);
            if (updated == 0) {
                throw new IllegalStateException("积分扣除失败，可能存在并发冲突");
            }

            // 减少库存
            if (product.getStock() != -1) {
                productMapper.decreaseStock(productId);
            }

            // 应用商品效果
            applyProductEffect(userId, product);

            // 更新订单状态
            orderMapper.updateStatus(order.getId(), "COMPLETED");

            response.put("success", true);
            response.put("message", "兑换成功");
            response.put("productName", product.getName());
            response.put("pointsSpent", product.getPrice());
            response.put("remainingPoints", newBalance);
            return response;
        } catch (Exception e) {
            log.error("兑换失败: userId={}, productId={}, error={}", userId, productId, e.getMessage());
            orderMapper.updateStatus(order.getId(), "FAILED");
            throw e;
        }
    }

    public List<VipOrder> getUserOrders(Long userId) {
        return orderMapper.findByUserId(userId);
    }

    private void applyProductEffect(Long userId, Product product) {
        if ("VIP".equals(product.getType())) {
            User user = userMapper.findById(userId);
            if (user == null) {
                throw new IllegalArgumentException("用户不存在");
            }
            LocalDateTime newExpiry = user.getVipExpiry() != null && user.getIsVip() && user.getVipExpiry().isAfter(LocalDateTime.now())
                    ? user.getVipExpiry().plusDays(product.getDuration())
                    : LocalDateTime.now().plusDays(product.getDuration());
            userMapper.updateVipStatus(userId, true, newExpiry);
        }
    }

    @Transactional
    public Map<String, Object> addProduct(String name, String description, int price, String type, int duration, int stock) {
        Map<String, Object> response = new HashMap<>();

        // 验证输入
        if (name == null || name.trim().isEmpty() || price < 0 || type == null || type.trim().isEmpty() || duration < 0 || stock < -1) {
            response.put("success", false);
            response.put("message", "无效的商品信息");
            return response;
        }

        // 创建商品
        Product product = new Product();
        product.setName(name.trim());
        product.setDescription(description != null ? description.trim() : null);
        product.setPrice(price);
        product.setType(type.trim());
        product.setDuration(duration);
        product.setStock(stock);
        productMapper.insertProduct(product);

        response.put("success", true);
        response.put("message", "商品添加成功");
        response.put("productId", product.getId());
        return response;
    }

    @Transactional
    public Map<String, Object> updateProduct(Long productId, String name, String description, Integer price, String type, Integer duration, Integer stock) {
        Map<String, Object> response = new HashMap<>();

        // 检查商品是否存在
        Product existing = productMapper.findById(productId);
        if (existing == null) {
            response.put("success", false);
            response.put("message", "商品不存在");
            return response;
        }

        // 更新字段（仅更新提供的非空字段）
        if (name != null && !name.trim().isEmpty()) {
            existing.setName(name.trim());
        }
        if (description != null) {
            existing.setDescription(description.trim());
        }
        if (price != null && price >= 0) {
            existing.setPrice(price);
        }
        if (type != null && !type.trim().isEmpty()) {
            existing.setType(type.trim());
        }
        if (duration != null && duration >= 0) {
            existing.setDuration(duration);
        }
        if (stock != null && stock >= -1) {
            existing.setStock(stock);
        }

        productMapper.updateProduct(existing);

        response.put("success", true);
        response.put("message", "商品更新成功");
        return response;
    }

    @Transactional
    public Map<String, Object> deleteProduct(Long productId) {
        Map<String, Object> response = new HashMap<>();

        // 检查商品是否存在
        Product existing = productMapper.findById(productId);
        if (existing == null) {
            response.put("success", false);
            response.put("message", "商品不存在");
            return response;
        }

        productMapper.deleteProduct(productId);

        response.put("success", true);
        response.put("message", "商品删除成功");
        return response;
    }

    public Map<String, Object> getAllProducts() {
        Map<String, Object> response = new HashMap<>();
        List<Product> products = productMapper.findAllProducts();
        response.put("success", true);
        response.put("products", products);
        return response;
    }
}